package com.iplant.aps.serviceimpl.dao.sfc;

import com.iplant.aps.service.mesenum.MESDBSource;
import com.iplant.aps.service.mesenum.MESException;
import com.iplant.aps.service.po.OutResult;
import com.iplant.aps.service.po.ServiceResult;
import com.iplant.aps.service.po.bms.BMSEmployee;
import com.iplant.aps.service.po.sfc.SFCOutMaterialConfigItem;
import com.iplant.aps.service.utils.StringUtils;
import com.iplant.aps.serviceimpl.dao.BaseDAO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;

import java.text.MessageFormat;
import java.util.*;

public class SFCOutMaterialConfigItemDAO extends BaseDAO {

    private static final Logger logger = LoggerFactory.getLogger(SFCOutMaterialConfigItemDAO.class);

    private static SFCOutMaterialConfigItemDAO Instance = null;

    private SFCOutMaterialConfigItemDAO() {
        super();
    }

    public static SFCOutMaterialConfigItemDAO getInstance() {
        if (Instance == null)
            Instance = new SFCOutMaterialConfigItemDAO();
        return Instance;
    }

    /**
     * 添加或修改
     */
    public int Update(BMSEmployee wLoginUser, SFCOutMaterialConfigItem wSFCOutMaterialConfigItem,
                      OutResult<Integer> wErrorCode) {
        int wResult = 0;
        try {
            ServiceResult<String> wInstance = this.GetDataBaseName(wLoginUser.getCompanyID(), MESDBSource.Basic,
                    wLoginUser.getID(), 0);
            wErrorCode.set(wInstance.ErrorCode);
            if (wErrorCode.Result != 0) {
                return wResult;
            }

            if (wSFCOutMaterialConfigItem == null)
                return 0;

            String wSQL = "";
            if (wSFCOutMaterialConfigItem.getID() <= 0) {
                wSQL = MessageFormat.format("INSERT INTO {0}.sfc_outmaterialconfigitem(ConfigID,SupplierName," +
                                "DeviceModel) VALUES(:ConfigID,:SupplierName,:DeviceModel);",
                        wInstance.Result);
            } else {
                wSQL = MessageFormat.format("UPDATE {0}.sfc_outmaterialconfigitem SET ConfigID = :ConfigID," +
                                "SupplierName = :SupplierName,DeviceModel = :DeviceModel WHERE ID = :ID;",
                        wInstance.Result);
            }

            wSQL = this.DMLChange(wSQL);

            Map<String, Object> wParamMap = new HashMap<>();

            wParamMap.put("ID", wSFCOutMaterialConfigItem.ID);
            wParamMap.put("ConfigID", wSFCOutMaterialConfigItem.ConfigID);
            wParamMap.put("SupplierName", wSFCOutMaterialConfigItem.SupplierName);
            wParamMap.put("DeviceModel", wSFCOutMaterialConfigItem.DeviceModel);

            KeyHolder keyHolder = new GeneratedKeyHolder();
            SqlParameterSource wSqlParameterSource = new MapSqlParameterSource(wParamMap);

            shrisJdbcTemplate.update(wSQL, wSqlParameterSource, keyHolder);

            if (wSFCOutMaterialConfigItem.getID() <= 0) {
                wResult = Objects.requireNonNull(keyHolder.getKey()).intValue();
                wSFCOutMaterialConfigItem.setID(wResult);
            } else {
                wResult = wSFCOutMaterialConfigItem.getID();
            }
        } catch (Exception ex) {
            wErrorCode.set(MESException.DBSQL.getValue());
            logger.error(ex.toString());
        }
        return wResult;
    }

    /**
     * 删除集合
     */
    public ServiceResult<Integer> DeleteList(BMSEmployee wLoginUser, List<SFCOutMaterialConfigItem> wList,
                                             OutResult<Integer> wErrorCode) {
        ServiceResult<Integer> wResult = new ServiceResult<>(0);
        try {
            ServiceResult<String> wInstance = this.GetDataBaseName(wLoginUser.getCompanyID(), MESDBSource.Basic,
                    wLoginUser.getID(), 0);
            wErrorCode.set(wInstance.ErrorCode);
            if (wErrorCode.Result != 0) {
                return wResult;
            }

            if (wList == null || wList.size() <= 0)
                return wResult;

            List<String> wIDList = new ArrayList<>();
            for (SFCOutMaterialConfigItem wItem : wList) {
                wIDList.add(String.valueOf(wItem.ID));
            }

            String wSql = MessageFormat.format("delete from {1}.sfc_outmaterialconfigitem WHERE ID IN({0}) ;",
                    String.join(",", wIDList), wInstance.Result);
            this.ExecuteSqlTransaction(wSql);
        } catch (Exception ex) {
            wErrorCode.set(MESException.DBSQL.getValue());
            logger.error(ex.toString());
        }
        return wResult;
    }

    /**
     * 查单条
     */
    public SFCOutMaterialConfigItem SelectByID(BMSEmployee wLoginUser, int wID, OutResult<Integer> wErrorCode) {
        SFCOutMaterialConfigItem wResult = new SFCOutMaterialConfigItem();
        try {
            ServiceResult<String> wInstance = this.GetDataBaseName(wLoginUser.getCompanyID(), MESDBSource.Basic,
                    wLoginUser.getID(), 0);
            wErrorCode.set(wInstance.ErrorCode);
            if (wErrorCode.Result != 0) {
                return wResult;
            }

            List<SFCOutMaterialConfigItem> wList = SelectList(wLoginUser, wID, -1, wErrorCode);
            if (wList == null || wList.size() != 1)
                return wResult;
            wResult = wList.get(0);
        } catch (Exception e) {
            wErrorCode.set(MESException.DBSQL.getValue());
            logger.error(e.toString());
        }
        return wResult;
    }

    /**
     * 条件查询集合
     */
    public List<SFCOutMaterialConfigItem> SelectList(BMSEmployee wLoginUser, int wID, int wConfigID,
                                                     OutResult<Integer> wErrorCode) {
        List<SFCOutMaterialConfigItem> wResultList = new ArrayList<>();
        try {
            ServiceResult<String> wInstance = this.GetDataBaseName(wLoginUser.getCompanyID(), MESDBSource.Basic,
                    wLoginUser.getID(), 0);
            wErrorCode.set(wInstance.ErrorCode);
            if (wErrorCode.Result != 0) {
                return wResultList;
            }

            String wSQL = MessageFormat.format(
                    "SELECT * FROM {0}.sfc_outmaterialconfigitem WHERE  1=1  and ( :wID <= 0 or :wID = ID ) and ( " +
                            ":wConfigID <= 0 or :wConfigID = ConfigID );",
                    wInstance.Result);

            Map<String, Object> wParamMap = new HashMap<>();

            wParamMap.put("wID", wID);
            wParamMap.put("wConfigID", wConfigID);

            wSQL = this.DMLChange(wSQL);

            List<Map<String, Object>> wQueryResult = shrisJdbcTemplate.queryForList(wSQL, wParamMap);

            for (Map<String, Object> wReader : wQueryResult) {
                SFCOutMaterialConfigItem wItem = new SFCOutMaterialConfigItem();

                wItem.ID = StringUtils.parseInt(wReader.get("ID"));
                wItem.ConfigID = StringUtils.parseInt(wReader.get("ConfigID"));
                wItem.SupplierName = StringUtils.parseString(wReader.get("SupplierName"));
                wItem.DeviceModel = StringUtils.parseString(wReader.get("DeviceModel"));

                wResultList.add(wItem);
            }
        } catch (Exception ex) {
            wErrorCode.set(MESException.DBSQL.getValue());
            logger.error(ex.toString());
        }
        return wResultList;
    }

    public List<SFCOutMaterialConfigItem> SelectList(BMSEmployee wLoginUser, List<Integer> wIDList,
                                                     OutResult<Integer> wErrorCode) {
        List<SFCOutMaterialConfigItem> wResultList = new ArrayList<>();
        try {
            ServiceResult<String> wInstance = this.GetDataBaseName(wLoginUser.getCompanyID(), MESDBSource.Basic,
                    wLoginUser.getID(), 0);
            wErrorCode.set(wInstance.ErrorCode);
            if (wErrorCode.Result != 0) {
                return wResultList;
            }

            if (wIDList == null || wIDList.size() <= 0) {
                return wResultList;
            }

            String wSQL = MessageFormat.format(
                    "SELECT * FROM {0}.sfc_outmaterialconfigitem WHERE ConfigID in ({1});",
                    wInstance.Result, StringUtils.Join(",", wIDList));

            Map<String, Object> wParamMap = new HashMap<>();

            wSQL = this.DMLChange(wSQL);

            List<Map<String, Object>> wQueryResult = shrisJdbcTemplate.queryForList(wSQL, wParamMap);

            for (Map<String, Object> wReader : wQueryResult) {
                SFCOutMaterialConfigItem wItem = new SFCOutMaterialConfigItem();

                wItem.ID = StringUtils.parseInt(wReader.get("ID"));
                wItem.ConfigID = StringUtils.parseInt(wReader.get("ConfigID"));
                wItem.SupplierName = StringUtils.parseString(wReader.get("SupplierName"));
                wItem.DeviceModel = StringUtils.parseString(wReader.get("DeviceModel"));

                wResultList.add(wItem);
            }
        } catch (Exception ex) {
            wErrorCode.set(MESException.DBSQL.getValue());
            logger.error(ex.toString());
        }
        return wResultList;
    }
}
